import { defineChannel } from "@elec/main/util/ipc-utils.ts";
import type { FileWriteStartArgs } from "@common/file-write-service-types.ts";
import path from "node:path";
import fs from "node:fs";

(() => {
  const holder = {
    stream: null as fs.WriteStream | null,
  };

  // 开始
  defineChannel("fs.stream.writer.start", (args: FileWriteStartArgs) => {
    return new Promise<void>((resolve, reject) => {
      let isRejected = false;
      const _reject = (e: any) => {
        if (isRejected) return;
        isRejected = true;
        reject(e);
      };

      try {
        const parentDir = path.dirname(args.file);
        if (!fs.existsSync(parentDir)) {
          fs.mkdirSync(parentDir, { recursive: true });
        }

        const stream = fs.createWriteStream(args.file, { flags: "w", encoding: "utf-8" });
        holder.stream = stream;
        holder.stream.on("open", () => {
          const isCsv = args.file.toLowerCase().endsWith(".csv");
          if (isCsv) {
            // CSV文件写入BOM,防止乱码
            stream.write(Buffer.from("\xEF\xBB\xBF", "binary"));
          }

          if (args.chunk) {
            stream.write(args.chunk);
          }
          resolve();
        });
        holder.stream.on("error", err => {
          _reject(err);
          console.error(`[file-write] stream error:`, err);
        });
      } catch (e: any) {
        _reject(e);
        console.error(`[file-write] start error:`, e);
      }
    });
  });

  // 写入
  defineChannel("fs.stream.writer.write", (chunk: string | Buffer) => {
    holder.stream?.write(chunk);
  });

  // 结束
  defineChannel("fs.stream.writer.close", () => {
    if (holder.stream) {
      holder.stream.end();
      holder.stream.close();
      holder.stream.destroy();
      holder.stream = null;
    }
  });
})();
